<template>
  <div class="app-container teacher-form-container">
    <div v-if="opt != 'add'">
      <el-descriptions title="">
        <el-descriptions-item label="企业名称">
          <el-tag style="margin-top: -5px" size="medium">{{
              form.enterpriseName
            }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="企业信息" name="first">
        <el-form  :model="form" ref="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="行政区域" >
                <Treeselect v-model="form.administrativeArea" :disabled="readonly"
                            :options="options" :flat="true" :show-count="true" :normalizer="normalizer"
                            placeholder="请选择行政区域" @input="administrativeAreaChange" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业名称" prop="enterpriseName">
                <el-input v-model="form.enterpriseName" placeholder="请输入企业名称"  :disabled="readonly" maxlength="30"  show-word-limit/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业性质" prop="enterpriseNature">
                <el-select v-model="form.enterpriseNature" placeholder="请选择企业性质" style="width:100%;"  :disabled="readonly">
                  <el-option
                    v-for="dict in dict.type.enterprise_nature"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册资金" prop="registeredCapital">
                <el-input v-model="form.registeredCapital" placeholder="请输入注册资金" :disabled="readonly" maxlength="50"  show-word-limit><template #append>万元</template></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
<!--            <el-col :span="8">-->
<!--              <el-form-item label="公司编号">-->
<!--                <el-input v-model="form.companyNo" :placeholder="noNew" :disabled="readonly" maxlength="30"  show-word-limit/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--            <el-col :span="12">-->
<!--              <el-form-item label="企业来源" prop="enterpriseSource">-->
<!--                <el-select v-model="form.enterpriseSource" placeholder="请选择企业来源" style="width: 100%;"    :disabled="readonly">-->
<!--                  <el-option-->
<!--                    v-for="dict in dict.type.enterprise_source"-->
<!--                    :key="dict.value"-->
<!--                    :label="dict.label"-->
<!--                    :value="dict.value"-->
<!--                  ></el-option>-->
<!--                </el-select>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="24">
              <el-form-item label="信息来源" prop="infoSource">
                <el-input v-model="form.infoSource" placeholder="请输入信息来源" :disabled="readonly" maxlength="50"  show-word-limit/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="所属行业" prop="industry">
<!--                <el-select v-model="form.industry" placeholder="请选择所属行业" style="width: 100%;"    :disabled="readonly">-->
<!--                  <el-option-->
<!--                    v-for="dict in dict.type.customer_industry"-->
<!--                    :key="dict.value"-->
<!--                    :label="dict.label"-->
<!--                    :value="dict.value"-->
<!--                  ></el-option>-->
<!--                </el-select>-->
                <treeselect
                  v-model="form.industry"
                  :options="industryOptions"
                  :normalizer="industryNormalizer"
                  :searchable="true"
                  :clearable="true"
                  placeholder="请选择所属行业"
                  style="width: 100%"
                  :disabled="readonly"
                  @input="handleIndustryChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="详情地址" prop="enterpriseAddress">
                <el-input  v-model="form.enterpriseAddress" placeholder="请输入详情地址" :disabled="readonly" maxlength="50"  show-word-limit/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="法人代表" prop="legalRepresentative">
                <el-input v-model="form.legalRepresentative" placeholder="请输入法人代表" :disabled="readonly" maxlength="10"  show-word-limit/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="成立日期" prop="establishmentDate">
                <el-date-picker clearable
                                style="width: 100%;"
                                v-model="form.establishmentDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择成立日期"
                                :disabled="readonly">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="税务号" prop="taxId">
                <el-input v-model="form.taxId" placeholder="请输入税务号" :disabled="readonly" maxlength="30"  show-word-limit/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="联系人"  >
                <el-input v-model="form.contacts" placeholder="请输入联系人" :disabled="readonly" maxlength="10"  show-word-limit/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话" >
                <el-input v-model="form.telephone" placeholder="请输入联系电话" :disabled="readonly" maxlength="20"  show-word-limit/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户账号" prop="account">
                <el-input v-model="form.account" placeholder="请输入开户账号" :disabled="readonly" maxlength="30"  show-word-limit/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
<!--            <el-col :span="8" style="height: 52px">-->
<!--              <el-form-item label="开发经理" prop="developManager" >-->
<!--                <el-input v-model="form.developmentName" placeholder="请输入开发经理" @focus="selectOpen(1)" :disabled="readonly"/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--            <el-col :span="8">-->
<!--              <el-form-item label="业务经理" prop="businessManager" >-->
<!--                <el-input v-model="form.businessManagerName" placeholder="请输入业务经理" @focus="selectOpen(2)" :disabled="readonly"/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="8">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;"  :disabled="readonly">
                  <el-option
                    v-for="dict in dict.type.seas_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属园区" prop="parkName">
                <el-select
                  v-model="form.parkName"
                  style="width: 305px"
                  placeholder="请选择所属园区"
                  :disabled="readonly"
                >
                  <el-option
                    v-for="dict in dict.type.belong_to_park"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="开户银行" prop="accountBank" >
                <el-input v-model="form.accountBank" placeholder="请输入开户银行" :disabled="readonly" maxlength="30"  show-word-limit/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建人" prop="createId" >
                <el-input v-model="form.userName" placeholder="请输入创建人"  disabled="true" :disabled="readonly"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建时间" prop="creatTime" >
                <el-date-picker clearable
                                v-model="form.creationTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择创建时间"
                                style="width: 100%"
                                disabled="true">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item label="经营范围" prop="businessScope">
                <el-input v-model="form.businessScope" placeholder="请输入经营范围" type="textarea" :disabled="readonly" maxlength="500"  show-word-limit/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业执照" prop="uploadFile">
                <file-view  v-if="showSeas"  :limit="1" :type="fileType" :businessId="form.businessLicense" :businessCode="businessCode" :disabled="readonly"></file-view>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: center;margin-top: 20px">
          <el-button type="primary" @click="submitForm" v-show="opt!=='select'">保 存</el-button>
          <el-button @click="cancel" v-show="opt!=='select'"  >关 闭</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="进展记录" name="progress" v-if="opt!=='add'">
        <el-tabs  type="card" class="records-tabs" v-model="activeTab">
          <el-tab-pane label="公海记录" name="seas">
            <Records :bId="this.id" @change="loadList" v-if="honorShow === 5"></Records>
          </el-tab-pane>
        </el-tabs>
        <div style="text-align: center;">
          <el-button  @click="cancel">关 闭</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="荣誉资质信息" name="second" v-if="opt!=='add'">
        <Honor v-if="honorShow===1"  :enterpriseId="form.enterpriseId" :enterpriseName="form.enterpriseName">
        </Honor>
        <div style="text-align: center;">
          <el-button  @click="cancel">关 闭</el-button>
        </div>
      </el-tab-pane>
<!--      <el-tab-pane label="项目资金" name="fund" v-if="opt!=='add'">-->
<!--          <Funding v-if="honorShow === 3" :enterpriseId="form.enterpriseId" :enterpriseName="form.enterpriseName">-->
<!--          </Funding>-->
<!--        <div style="text-align: center;">-->
<!--          <el-button  @click="cancel">关 闭</el-button>-->
<!--        </div>-->
<!--      </el-tab-pane>-->
<!--      <el-tab-pane label="有效商机信息" name="businessinfo"  v-if="opt==='select'"  >-->
<!--        <Businessinfo v-if="honorShow === 4" :enterpriseId="form.enterpriseId" :enterpriseName="form.enterpriseName">-->
<!--        </Businessinfo>-->
<!--        <div style="text-align: center;">-->
<!--          <el-button type="primary" @click="cancel">关 闭</el-button>-->
<!--        </div>-->
<!--      </el-tab-pane>-->
<!--      <el-tab-pane label="合同信息" name="contract"  v-if="opt==='select'"  >-->
<!--        <div style="text-align: center;">-->
<!--          <el-button type="primary" @click="cancel">关 闭</el-button>-->
<!--        </div>-->
<!--      </el-tab-pane>-->
<!--      <el-tab-pane label="交付信息" name="deliver"  v-if="opt==='select'"  >-->
<!--        <div style="text-align: center;">-->
<!--          <el-button type="primary" @click="cancel">关 闭</el-button>-->
<!--        </div>-->
<!--      </el-tab-pane>-->
      <el-tab-pane label="人员信息" name="third" v-if="opt==='select'" >
        <Person v-if="honorShow===2"  :enterpriseId="form.enterpriseId"  ref="person" :isEnter="true"
                :enterpriseName="form.enterpriseName" :show-close="false">
        </Person>
        <div style="text-align: center;">
          <el-button  @click="cancel">关 闭</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
    <select-user ref="select"  :type="userType" :sign="sign" @ok="selectUser"></select-user>
  </div>
</template>
<script>
import { listRecords, getRecords, delRecords, addRecords, updateRecords } from "@/api/enterprise/records";
import { listSeas, getSeas, delSeas, addSeas, updateSeas,getMaxEnterpriseNo } from "@/api/highSeas/seas";
import { listArea } from "@/api/area/area";
import {listType} from "@/api/maintype/type";
import FileView from "@/components/FileView/index"
import SelectUser from "../../system/role/selectUser.vue";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Honor from "../../honor/index.vue";
import Person from "../person/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Funding from "../../project/funding/index.vue";
import Businessinfo from "../businessinfo/index.vue";
import Records from "./records.vue";
import person from "../person/index.vue";
import { getIndustryTree } from "@/api/enterprise/industry";
import SeasRecords from "./seasRecords.vue";
export default {
  name: "Info",
  dicts: ['enterprise_nature','customer_industry','enterprise_records','seas_status','enterprise_source','belong_to_park'],
  components: {SeasRecords, Businessinfo, Funding, Treeselect,SelectUser,FileView,Honor,Person,Records },
  props: {
    opt: {
      type:  String,
      default:""
    },
    id:{
      type: String,
      default:""
    },
    index:{
      type: Number,
      default:null
    },
    classificationId:{
      type:String,
      default:null
    }
  },
  data() {
    var developManager = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('开发经理不能为空'));
      }
      return callback()
    };
    var businessManager = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('业务经理不能为空'));
      }
      return callback()
    };
    var contacts = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('联系人不能为空'));
      }
      return callback()
    };
    return {
      fileType:0,
      industryOptions: [], // 行业树形数据
      userType:"1",
      businessCode:'seas',
      // 遮罩层
      loading: true,
      optionsClass:null,
      // 选中数组
      ids: [],
      enterpriseNo:"",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //附件上传
      showSeas:null,
      noNew:"当前公司编号为:",
      //是否只读
      readonly:false,
      // 总条数
      total: 0,
      // 企业信息表格数据
      recordsList: [],
      enterpriseinfo:'enterpriseinfo',
      activeTab:'seas',
      // 弹出层标题
      title: "",
      sign:'1',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        enterpriseId: null,
      },
      // 表单参数
      form: {
        markAs:1,
      },
      honorShow:'0',
      // 表单校验
      rules: {
        enterpriseName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
        administrativeArea: [
          { required: true, message: "行政区域不能为空", trigger: "change" }
        ],
        enterpriseNature: [
          {required: true, message: "企业性质不能为空", trigger: "change" }
        ],
        contacts: [
          {required: true, validator: contacts, trigger: "change" }
        ],
        telephone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" }
        ],
        developManager: [
          { required: true, validator: developManager, trigger: "change" }
        ],
        businessManager: [
          { required: true, validator: businessManager, trigger: "change"  }
        ],
        industry: [
          { required: true, message: "所属行业不能为空", trigger: "change"  }
        ],
        enterpriseAddress:[
          { required: true, message: "详情地址不能为空", trigger: "change"  }
        ],
        companyNo: [
          {   required: true, message: "公司编号不能为空", trigger: "change" },
          {   pattern: /^[0-9]*$/,
            message: "公司编号只能输入数字",
            trigger: "blur"
          }
        ],
      },
      //行政区域
      options:null,
      zValue:0,
      //复选框
      markAs:['1'],
      //选显卡默认选中
      activeName: 'first',
      //
      show:'',
      //上传按钮隐藏
      isShow:true,
      url:'',
    };
  },
  created() {
    this.listType();
    this.getMaxEnterpriseNoNo();
    this.getIndustryTree();
    console.log(this.id)
    if(this.opt==="edit" && this.id !==''){
      this.fileType=1;
      this.handleUpdate(this.id)
      this.readonly=false;
    }
    if(this.opt==="add"){
     this.id='';
      this.fileType=0;
      this.form.creationTime=new Date();
      this.form.userName=this.$store.state.user.info.nickName;
      this.form.businessLicense=new Date().getTime();
      this.showSeas=true;
     if (this.classificationId!==null){
       this.form.classificationId=this.classificationId;
     }else {
       this.form.classificationId='650c44e1-b575-4b62-9d54-1ba9d1e8abb7'
     }
      this.readonly=false;
    }
    if (this.opt==='select'){
      this.fileType=2;
      this.readonly=true;
      this.handleUpdate(this.id)
    }
    this.area();
  },
  //监听父组件传递的boolean值,用于关闭弹窗后，数据重新加载
  watch: {
    id: function(newValue, oldValue) {
      if (this.opt==='select'){
        this.fileType=2;
        this.readonly=true;
        this.handleUpdate(this.id)
      }
      this.area();
      this.listType();
      console.log(this.id)
      if(this.opt==="edit"){
        this.fileType=1;
        this.readonly=false;
        this.handleUpdate(this.id)
      }
      if(this.opt==="add"){
        this.id='';
        this.fileType=0;
        this.readonly=false;
        this.form.creationTime=new Date();
        this.form.userName=this.$store.state.user.name;
        this.form.businessLicense=new Date().getTime();
        this.showSeas=true;
        this.form.classificationId='650c44e1-b575-4b62-9d54-1ba9d1e8abb7'
      }
    },
  },
  methods: {
    // 取消按钮
    cancel() {
      if (this.opt==='add'){
        this.$emit('change',false);
      }else {
        // this.id='';
        this.open = false;
        this.reset();
        // this.$emit('change',true);
        this.$emit('change',false);
      }

    },
    rowAdd(){
      this.recordsList.push({recordsId:new Date().getTime(),followTime:this.parseTime(new Date(),'{y}-{m}-{d} {hh}:{ss}'),followPerson:this.$store.state.user.name,annex:new Date().getTime()})
    },
    // 获取行业树形数据
    getIndustryTree() {
      getIndustryTree().then(response => {
        if (response.code === 200) {
          this.industryOptions = response.data;
          console.log('行业数据:', this.industryOptions);
        } else {
          this.$modal.msgError(response.msg);
        }
      }).catch(error => {
        console.error('获取行业数据失败:', error);
        this.$modal.msgError('获取行业数据失败');
      });
    },
    administrativeAreaChange(val) {
      // console.log('parentId变化', val);
      this.$nextTick(() => {
        this.$refs.form.validateField('administrativeArea');
      })
    },
    //获取树节点数据
    listType(){
      listType({typeCode:'seas'}).then(res=>{
        console.log(res);
        this.optionsClass=res.data;
      })
    },
    // 处理行业选择变化
    handleIndustryChange(value) {
      if (value) {
        // 根据选择的行业ID更新industryType
        const findIndustryType = (options, targetId) => {
          for (const option of options) {
            if (option.industryId === targetId) {
              // 根据行业的层级设置industryType
              this.form.industryType = option.levelType === 1 ? "0" :
                option.levelType === 2 ? "1" : "2";
              return true;
            }
            if (option.children) {
              if (findIndustryType(option.children, targetId)) {
                return true;
              }
            }
          }
          return false;
        };

        findIndustryType(this.industryOptions, value);
      }
    },
    loadList() {
      this.$emit('change', this.zValue);
    },
    // 格式化行业树形数据
    industryNormalizer(node) {
      return {
        id: node.industryId,
        label: node.name,
        children: node.children && node.children.length > 0 ? node.children : null
      };
    },
    handlesubmit(row){
      row.enterpriseId=this.form.enterpriseId
      addRecords(row).then(response => {
        this.$modal.msgSuccess("保存成功");
      });
    },
    getMaxEnterpriseNoNo(){
      getMaxEnterpriseNo().then(response => {
        if(response==""||response==null){
          this.noNew+="000"
        }else{
          this.noNew+=response
          this.enterpriseNo = response
        }
      })
    },
    selectActiveName() {
      console.log("是否执行")
      this.activeName = 'first'
      this.honorShow='0';
    },
    area(){
      listArea({}).then(response => {
        this.options = response.data;
      });
    },
    selectUser(userId,userName,phone){
      if(this.show=='2'){
        this.$set(this.form, 'businessManagerName', userName)
        this.$set(this.form, 'businessManager', userId)
      }else if(this.show=='1'){
        this.$set(this.form, 'developmentName', userName)
        this.$set(this.form, 'developManager', userId)
      }else{
        this.$set(this.form, 'contacts', userName)
        this.$set(this.form, 'telephone', phone)
      }
    },
    selectOpen(type){
      this.show=type
      this.$refs.select.show();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    getFile(data){
      console.log(data)
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.areaId,
        label: node.areaName,
        isDisabled: false,
        children: node.list && node.list.length > 0 ? node.list : 0

      }
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.reset();
      getSeas(id).then(response => {
        this.form = response.data;
        console.log(this.form)
        if (this.form.businessLicense==null){
          this.form.businessLicense=new Date().getTime();
        }
        this.recordsList=response.data.records
        this.showSeas=true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(this.opt=="add"){
        this.$refs["form"].validate(valid => {
          if (valid) {
            getMaxEnterpriseNo().then(responseNo => {
                  addSeas(this.form).then(response => {
                    if (response.code===500){
                      this.$message.error(response.msg);
                    }else {
                      this.$modal.msgSuccess("新增成功");
                      this.showSeas=false;
                      this.cancel();
                    }
                  });
            })

          }
        });
      }else {
        this.$refs["form"].validate(valid => {
            if (valid) {
              if (this.form.enterpriseId != null) {
                updateSeas(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.$refs.person.getList();
                  this.showSeas = false;
                  this.cancel();
                });
              }
            }
          }
        )}


    },
    // 表单重置
    reset() {
      this.form = {
        enterpriseId: null,
        enterpriseName: null,
        enterpriseSource: null,
        enterpriseAbbreviation: null,
        administrativeArea: null,
        legalRepresentative: null,
        establishmentDate: null,
        contractAmount: null,
        enterpriseLabel: null,
        registeredCapital: null,
        industry: null,
        contacts: null,
        telephone: null,
        bankName: null,
        taxId: null,
        developmentId: null,
        transactionId: null,
        developmentManager: null,
        businessManager: null,
        enterpriseAddress: null,
        businessScope: null,
        enterpriseNature: null,
        markAs: null,
        belongTo: null,
        creationTime: null,
        operateTime: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        delFlag: null,
        id:'',
        infoSource:null,
        parkName:null,
      };
      this.resetForm("form");
    },
    handleClick(tab, event){
      if(tab.name==='second'){
        this.honorShow=1
      }
      if(tab.name==='third'){
        this.honorShow=2
      }
      if (tab.name==='fund'){
        this.honorShow=3
      }
      if (tab.name==='businessinfo'){
        this.honorShow=4
      }
      if (tab.name==='progress'){
        this.honorShow=5
      }
    },

  }
};
</script>
<style scoped>
.el-col {
  height: 55px;
}
.teacher-form-container {
  overflow-y: auto;
  overflow-x: auto;
  padding: 16px;
  max-width: 100%;
  max-height: 75vh;
  box-sizing: border-box;
}
.el-descriptions-item__label:not(.is-bordered-label) {
  font-size: 12px;
  margin-top: 4px;
}
</style>
